$(function () {

    // jobGroup change, job list init and select
    $("#jobGroup").on("change", function () {
        var jobGroup = $(this).children('option:selected').val();
        $.ajax({
            type: 'POST',
            async: false,   // async, avoid js invoke pagelist before jobId data init
            url: base_url + '/joblog/getJobsByGroup',
            data: {"jobGroup": jobGroup},
            dataType: "json",
            success: function (data) {
                if (data.code == 200) {
                    $("#jobId").html('<option value="0" >' + I18n.system_all + '</option>');
                    $.each(data.content, function (n, value) {
                        $("#jobId").append('<option value="' + value.id + '" >' + value.jobDesc + '</option>');
                    });
                    if ($("#jobId").attr("paramVal")) {
                        $("#jobId").find("option[value='" + $("#jobId").attr("paramVal") + "']").attr("selected", true);
                    }
                } else {
                    layer.open({
                        title: I18n.system_tips,
                        btn: [I18n.system_ok],
                        content: (data.msg || I18n.system_api_error),
                        icon: '2'
                    });
                }
            },
        });
    });
    if ($("#jobGroup").attr("paramVal")) {
        $("#jobGroup").find("option[value='" + $("#jobGroup").attr("paramVal") + "']").attr("selected", true);
        $("#jobGroup").change();
    }

    // filter Time
    var rangesConf = {};
    rangesConf[I18n.daterangepicker_ranges_today] = [moment().startOf('day'), moment().endOf('day')];
    rangesConf[I18n.daterangepicker_ranges_yesterday] = [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')];
    rangesConf[I18n.daterangepicker_ranges_last_month] = [moment().subtract(1, 'months').startOf('month'), moment().subtract(1, 'months').endOf('month')];
    rangesConf[I18n.daterangepicker_ranges_recent_week] = [moment().subtract(1, 'weeks').startOf('day'), moment().endOf('day')];
    rangesConf[I18n.daterangepicker_ranges_recent_month] = [moment().subtract(1, 'months').startOf('day'), moment().endOf('day')];

    $('#filterTime').daterangepicker({
        autoApply: false,
        singleDatePicker: false,
        showDropdowns: false,        // 是否显示年月选择条件
        timePicker: true, 			// 是否显示小时和分钟选择条件
        timePickerIncrement: 10, 	// 时间的增量，单位为分钟
        timePicker24Hour: true,
        opens: 'left', //日期选择框的弹出位置
        ranges: rangesConf,
        locale: {
            format: 'YYYY-MM-DD HH:mm:ss',
            separator: ' - ',
            customRangeLabel: I18n.daterangepicker_custom_name,
            applyLabel: I18n.system_ok,
            cancelLabel: I18n.system_cancel,
            fromLabel: I18n.daterangepicker_custom_starttime,
            toLabel: I18n.daterangepicker_custom_endtime,
            daysOfWeek: I18n.daterangepicker_custom_daysofweek.split(','),        // '日', '一', '二', '三', '四', '五', '六'
            monthNames: I18n.daterangepicker_custom_monthnames.split(','),        // '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'
            firstDay: 1
        },
        startDate: rangesConf[I18n.daterangepicker_ranges_recent_week][0],
        endDate: rangesConf[I18n.daterangepicker_ranges_recent_week][1]
    });

    // init date tables
    var costTable = $("#jobcost_list").dataTable({
        "deferRender": true,
        "processing": true,
        "serverSide": true,
        "ajax": {
            url: base_url + "/jobcost/pageList",
            type: "post",
            data: function (d) {
                var obj = {};
                obj.jobGroup = $('#jobGroup').val();
                obj.jobId = $('#jobId').val();
                obj.filterTime = $('#filterTime').val();
                obj.start = d.start;
                obj.length = d.length;
                return obj;
            }
        },
        "searching": false,
        "ordering": false,
        //"scrollX": false,
        "columns": [
            {
                "data": 'jobId',
                "visible": true,
                "width": '10%'
            },
            {
                "data": 'jobDesc',
                "visible": true,
                "width": '10%'
            },
            {"data": 'jobGroup', "visible": false},
            {
                "data": 'triggerCount',
                "width": '10%',
                "render": function (data, type, row) {
                    return data;
                }
            },
            {
                "data": 'minCost',
                "width": '10%',
                "render": function (data, type, row) {
                    return formatTime(data);
                }
            },
            {
                "data": 'maxCost',
                "width": '10%',
                "render": function (data, type, row) {
                    return formatTime(data);
                }
            },
            {
                "data": 'avgCost',
                "width": '10%',
                "render": function (data, type, row) {
                    return colorTime(data);
                }
            },
            {
                "data": 'handleMsg' ,
                "bSortable": false,
                "width":'10%',
                "render": function ( data, type, row ) {
                    return '<a href="jobcost/detail/' + row.jobId + '" target="_blank">'+ I18n.system_show +'</a>';
                }
            }
        ],
        "language": {
            "sProcessing": I18n.dataTable_sProcessing,
            "sLengthMenu": I18n.dataTable_sLengthMenu,
            "sZeroRecords": I18n.dataTable_sZeroRecords,
            "sInfo": I18n.dataTable_sInfo,
            "sInfoEmpty": I18n.dataTable_sInfoEmpty,
            "sInfoFiltered": I18n.dataTable_sInfoFiltered,
            "sInfoPostFix": "",
            "sSearch": I18n.dataTable_sSearch,
            "sUrl": "",
            "sEmptyTable": I18n.dataTable_sEmptyTable,
            "sLoadingRecords": I18n.dataTable_sLoadingRecords,
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": I18n.dataTable_sFirst,
                "sPrevious": I18n.dataTable_sPrevious,
                "sNext": I18n.dataTable_sNext,
                "sLast": I18n.dataTable_sLast
            },
            "oAria": {
                "sSortAscending": I18n.dataTable_sSortAscending,
                "sSortDescending": I18n.dataTable_sSortDescending
            }
        }
    });
    costTable.on('xhr.dt', function (e, settings, json, xhr) {
        if (json.code && json.code !== 200) {
            layer.msg(json.msg || I18n.system_api_error);
        }
    });

    // search Btn
    $('#searchBtn').on('click', function () {
        costTable.fnDraw();
    });

    function colorTime(data) {
        let time = (data / 1000).toFixed(0);
        if (time <= 60) { // 不超过1分钟
            return '<span style="color: green">' + formatTime(data) + '</span>';
        } else if (time <= 300) { // 不超过5分钟
            return '<span style="color: blue">' + formatTime(data) + '</span>';
        } else if (time <= 600) { // 不超过10分钟
            return '<span style="color: orange">' + formatTime(data) + '</span>';
        } else { // 超过10分钟
            return '<span style="color: red">' + formatTime(data) + '</span>';
        }
    }

    function formatTime(data) {
        let time = (data / 1000).toFixed(0);
        let hour = Math.floor(time / 3600);
        let minute = Math.floor((time % 3600) / 60);
        let seconds = (time % 3600) % 60;

        if (time <= 60) { // 秒级
            return time + I18n.jobcost_second;
        } else if (time <= 3600) { // 分钟级
            return minute + I18n.jobcost_minute + seconds  + I18n.jobcost_second;
        } else { // 小时级
            return hour + I18n.jobcost_hour + minute + I18n.jobcost_minute + seconds + I18n.jobcost_second;
        }
    }

});
